import axios from 'axios'
// 导入toast
import { Toast } from 'vant'
import store from '@/store'
import router from '@/router'
import { authorizationsPut } from '@/api/user.js'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})
// 请求拦截
_axios.interceptors.request.use(
  config => {
    console.log('config:', config)
    // config.headers.Authorization = `Bearer ${store.state.user.token}`
    // console.log('token:', store.getters.token)
    // config.headers.Authorization = `Bearer ${store.getters.token}`
    // config.headers.Authorization = `Bearer ${store.getters['user/getToken']}`
    if (!config.noToken) {
      config.headers.Authorization = `Bearer ${store.getters['user/getToken']}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截
_axios.interceptors.response.use(
  res => {
    return res.data
  },
  async error => {
    if (error.response.status === 401) {
      try {
        // 如果刷新token出错了就按以前方式处理
        const restoken = await authorizationsPut()
        console.log('refreshToken', restoken)
        // 存储token,让以前的请求正常进行
        store.commit('user/setToken', restoken.data.token)
        return _axios(error.config)
      } catch {
        // 统一错误处理
        if (
          !error.config.noError &&
          error.response.data &&
          error.response.data.message
        ) {
          Toast.fail(error.response.data.message)
        }
        // 删除token
        store.commit('user/setToken', '')
        // 跳转到登录页,router.currentRoute当前路由信息
        router.push('/login?redirect=' + router.currentRoute.fullPath)
      }
      // 删除token跳转到登录页
      // if (error.response.status === 401) {
      //   store.commit('user/setToken', '')
      //   router.push('/login?redirect=' + router.currentRoute.fullPath)
      // }
      // console.log('错误:', [error])
      // return Promise.reject(error)
    } else {
      if (
        !error.config.noError &&
        error.response.data &&
        error.response.data.message
      ) {
        Toast.fail(error.response.data.message)
      }
    }
    console.log('错误:', [error])
    return Promise.reject(error)
  }
)
export default _axios
